package com.example.computer_component_manager.fragment.impl

import android.app.Activity
import android.app.AlertDialog
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TableLayout
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.android.volley.Request
import com.bumptech.glide.Glide
import com.example.computer_component_manager.R
import com.example.computer_component_manager.activity.GpuEditorActivity
import com.example.computer_component_manager.bean.AllGpuInfo
import com.example.computer_component_manager.databinding.FragmentComponentRecyclerBinding
import com.example.computer_component_manager.databinding.GpuItemBinding
import com.example.computer_component_manager.fragment.ComponentListFragment
import com.example.computer_component_manager.util.DbUtil
import com.example.computer_component_manager.util.ToastUtil
import com.example.computer_component_manager.volley.MyJsonArrayRequest
import com.example.computer_component_manager.volley.MyJsonObjectRequest
import com.example.computer_component_manager.volley.VolleyApplication

/**
 * 显卡管理碎片(Fragment)
 *
 * @author 1923111015董寺卓
 */

class GpuFragment : ComponentListFragment() {

    companion object {

        var allGpuInfo = AllGpuInfo()

    }

    private lateinit var binding: FragmentComponentRecyclerBinding

    private val adapter = GpuAdapter()


    override fun refreshData() {
        val getAllGpuInfoRequest = MyJsonArrayRequest(Request.Method.GET,
            DbUtil.GET_ALL_GPU_INFO_URL, null, {
                allGpuInfo = DbUtil.gson.fromJson(it.toString(), AllGpuInfo::class.java)
                closeAllItem()
                adapter.notifyDataSetChanged()
            }, {
                ToastUtil.showShortError(context)
            })
        VolleyApplication.instance.requestQueue.add(getAllGpuInfoRequest)
    }

    override fun closeAllItem() {
        for (i in 0..adapter.itemCount) {
            binding.rvComponentList.findViewHolderForAdapterPosition(i)
                ?.itemView?.findViewById<TableLayout>(R.id.tlGpuItemInfo)?.visibility = View.GONE
        }
    }

    override fun gotoItemEditor(position: Int?) {
        // 获取显卡品牌
        val gotoEditorRequest = MyJsonArrayRequest(
            Request.Method.GET, DbUtil.GET_GPU_BRANDS_URL, null, {
                val intent = Intent(context, GpuEditorActivity::class.java)
                position?.let { value -> intent.putExtra("gpuItemPosition", value) }
                intent.putExtra("gpuBrands", it.toString())
                startActivityForResult(intent, DbUtil.GPU_EDITOR_REQUEST_CODE)
            }, {
                ToastUtil.showShortError(context)
            }
        )
        VolleyApplication.instance.requestQueue.add(gotoEditorRequest)
    }

    override fun deleteItem(position: Int) {
        val gpuInfoItem = allGpuInfo[position]
        val delGpuItemRequest = MyJsonObjectRequest(Request.Method.DELETE,
            "${DbUtil.API_PREFIX}/gpu/${gpuInfoItem.id}",
            null, {
                ToastUtil.showShortSuccess(context, it.optString("msg"))
                refreshData()
            }, {
                ToastUtil.showShortError(context)
            })
        VolleyApplication.instance.requestQueue.add(delGpuItemRequest)
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?,
    ): View {
        binding = FragmentComponentRecyclerBinding.inflate(inflater)
        binding.rvComponentList.layoutManager = LinearLayoutManager(context)
        binding.rvComponentList.adapter = adapter
        refreshData()
        binding.ibRefresh.setOnClickListener { refreshData() }
        binding.ibAdd.setOnClickListener { gotoItemEditor(null) }
        return binding.root
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (requestCode == DbUtil.GPU_EDITOR_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
            Toast.makeText(
                context, resources.getString(R.string.success), Toast.LENGTH_SHORT).show()
            refreshData()
        }
    }

    inner class GpuAdapter : RecyclerView.Adapter<GpuAdapter.GpuHolder>() {

        inner class GpuHolder(val binding: GpuItemBinding) : RecyclerView.ViewHolder(binding.root)

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): GpuHolder {
            val binding = GpuItemBinding.inflate(layoutInflater, parent, false)
            binding.root.setOnClickListener {
                binding.tlGpuItemInfo.visibility =
                    if (binding.tlGpuItemInfo.visibility == View.GONE) View.VISIBLE else View.GONE
            }
            return GpuHolder(binding)
        }

        override fun onBindViewHolder(holder: GpuHolder, position: Int) {
            val gpu = allGpuInfo[position]
            Glide.with(context!!).load(gpu.imgUrl).into(holder.binding.ivGpuItemImage)
            holder.binding.tvGpuItemType.text = gpu.type
            holder.binding.tvGpuItemPrice.text =
                resources.getString(R.string.yuan_format).format(gpu.consumerPrice)
            holder.binding.tvGpuItemBrandName.text = gpu.brand.name
            holder.binding.tvGpuItemVideoMemory.text =
                resources.getString(R.string.gigabyte_format).format(gpu.size)
            holder.binding.btnGpuEdit.setOnClickListener { gotoItemEditor(position) }
            holder.binding.root.setOnLongClickListener {
                AlertDialog.Builder(context)
                    .setTitle(resources.getString(R.string.confirm_del))
                    .setPositiveButton(resources.getString(R.string.ok)) { _, _ ->
                        deleteItem(position)
                    }.setNegativeButton(resources.getString(R.string.cancel)) { _, _ -> }.show()
                return@setOnLongClickListener true
            }
        }

        override fun getItemCount() = allGpuInfo.size

    }

}